package com.zy.cloud.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.zy.cloud.entity.CommonResult;
import com.zy.cloud.service.UserHystrixService;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @ClassName: UserHystrixController
 * @Description: #TODO
 * @Author: yanzy
 * @Date: 2021/3/3 22:18
 */
@RestController
@DefaultProperties(defaultFallback = "defaultFallBackFuc")  // 配置通用的降级方法
public class UserHystrixController {

    @Resource
    private UserHystrixService userHystrixService;

    @GetMapping("/hystrix/user/ok/{id}")
    public CommonResult<String> reqOk(@PathVariable("id") Integer id) {
        String s = userHystrixService.reqOk(id);
        if (StringUtils.isEmpty(s)) {
            return new CommonResult<String>(201, "请求失败");
        }
        return new CommonResult<String>(200, "请求成功", s);
    }

    @GetMapping("/hystrix/user/timeout/{id}")
    /*@HystrixCommand(fallbackMethod = "reqTimeOutHandler", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000")
    })*/
    @HystrixCommand     // 设置通用降级方法，还需要指定降级
    public CommonResult<String> reqTimeOut(@PathVariable("id") Integer id) {
        String s = userHystrixService.reqTimeOut(id);
        if (StringUtils.isEmpty(s)) {
            return new CommonResult<String>(201, "请求失败");
        }
        return new CommonResult<String>(200, "请求成功", s);
    }

    /**
     * 降级方法 返回值 必须与 被降级方法返回值相同 否则报错
     * @param id
     * @return
     */
    public CommonResult<String> reqTimeOutHandler(Integer id) {

        return new CommonResult<String>(200, "服务提供方太慢了...嫌弃o(╥﹏╥)o ~~~~" + id);
    }

    // ===============  全局 fallback方法

    public CommonResult<String> defaultFallBackFuc() {

        return new CommonResult<String>(200, "通用fallback方法 O(∩_∩)O哈哈~ ~~~~");
    }
}
